<script setup>
import { ref, onMounted, onActivated, computed } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElButton, ElMessageBox } from 'element-plus'
import { useDataIterator, IteratorFactory } from '@/utils/data-iterators'

const loading = ref(false)
const items = ref([])
const useIteratorMode = ref(false)

// 使用迭代器进行分组显示
const groupedAppointments = computed(() => {
  if (!useIteratorMode.value || items.value.length === 0) {
    return [{ groupName: 'all', appointments: items.value, count: items.value.length }]
  }

  // 创建预约迭代器，按状态分组
  const appointmentIterator = IteratorFactory.createAppointmentIterator(
    items.value,
    'status'
  )

  const groups = []
  let result = appointmentIterator.next()
  while (!result.done) {
    groups.push(result.value)
    result = appointmentIterator.next()
  }

  return groups
})

async function fetchMyAppointments() {
  loading.value = true
  
  // 检查用户是否已登录
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    console.error('❌ 用户未登录')
    ElMessage.error('请先登录')
    loading.value = false
    return
  }
  
  console.log('🔑 找到认证token:', token.substring(0, 20) + '...')
  
  try {
    // 优先使用基础API
    console.log('📡 正在调用基础API: /api/appointments/my')
    const {data} = await request.get('/api/appointments/my')
    
    console.log('📥 API响应:', data)
    
    if (data && data.code === 0) {
      items.value = data.data || []
      console.log('✅ 获取预约成功:', items.value.length, '条记录')
    } else {
      // 如果基础API失败，尝试迭代器API
      console.warn('基础API失败，尝试迭代器API')
      const groupBy = useIteratorMode.value ? 'status' : 'none'
      const iteratorResponse = await request.get(`/api/appointments/iterator/?group_by=${groupBy}`)
      
      if (iteratorResponse.data && iteratorResponse.data.code === 0) {
        items.value = iteratorResponse.data.data.appointments || []
        console.log('🔄 使用迭代器API获取预约:', items.value.length, '条记录')
      } else {
        throw new Error(iteratorResponse.data?.msg || data?.msg || '获取预约失败')
      }
    }
  } catch (err) {
    console.error('❌ 获取预约失败:', err)
    ElMessage.error(err.message || '获取预约失败，请稍后重试')
    items.value = [] // 确保清空数据
  } finally {
    loading.value = false
  }
}

// 切换显示模式
  function toggleIteratorMode() {
    useIteratorMode.value = !useIteratorMode.value
    ElMessage.info(useIteratorMode.value ? '已启用迭代器分组模式' : '已关闭迭代器分组模式')
  }

// 演示迭代器统计功能
  function showIteratorStats() {
    if (items.value.length === 0) {
      ElMessage.warning('暂无预约数据')
      return
    }

    const iterator = IteratorFactory.createFilteredIterator(
        items.value,
        appointment => appointment.status === 'confirmed'
    )

    let confirmedCount = 0
    let result = iterator.next()
    while (!result.done) {
      confirmedCount++
      result = iterator.next()
    }

    ElMessage.success(`统计结果：共有 ${confirmedCount} 个已确认的预约`)
  }

// 获取状态中文名称
  function getStatusName(status) {
    const statusMap = {
      'pending': '待确认',
      'confirmed': '已确认',
      'completed': '已完成',
      'cancelled': '已取消',
      'no_show': '未到诊',
      'all': '全部'
    }
    return statusMap[status] || status
  }

// 使用迭代器取消预约
  async function cancelAppointment(appointmentNo) {
    try {
      ElMessage.info('正在使用迭代器取消预约...')

      const {data} = await request.post('/api/appointments/cancel/', {
        appointment_no: appointmentNo
      })

      if (data.code === 0) {
        ElMessage.success('预约取消成功！')

        // 显示统计信息
        const stats = data.data.statistics
        ElMessage.info(`当前统计：${stats.total} 个预约，${stats.cancelled} 个已取消`)

        // 重新获取数据
        fetchMyAppointments()
      } else {
        ElMessage.error(data.msg || '取消预约失败')
      }
    } catch (error) {
      console.error('取消预约错误:', error)
      ElMessage.error('取消预约失败，请稍后重试')
    }
  }

// 确认取消预约
  function confirmCancelAppointment(appointment) {
    ElMessageBox.confirm(
        `确定要取消预约 ${appointment.appointment_no} 吗？`,
        '取消预约',
        {
          confirmButtonText: '确定取消',
          cancelButtonText: '暂不取消',
          type: 'warning',
        }
    ).then(() => {
      cancelAppointment(appointment.appointment_no)
    }).catch(() => {
      ElMessage.info('已取消操作')
    })
  }

onMounted(fetchMyAppointments)
onActivated(fetchMyAppointments) // 页面激活时也刷新数据，确保显示最新预约
</script>

<template>
  <div class="my-appts" v-loading="loading">
    <div class="header">
      <h2>我的预约</h2>
      <div class="actions">
        <el-button @click="toggleIteratorMode" :type="useIteratorMode ? 'success' : 'default'">
          {{ useIteratorMode ? '关闭分组' : '开启分组' }}
        </el-button>
        <el-button @click="showIteratorStats" type="info">
          统计预约
        </el-button>
      </div>
    </div>

    <h2>我的预约</h2>
    <div v-if="items.length === 0" class="empty">暂无预约记录</div>
    
    <!-- 普通列表显示模式 -->
    <div v-else-if="!useIteratorMode" class="list">
      <div v-for="it in items" :key="it.appointment_no" class="card">
        <div class="row1">
          <div class="doctor">{{ it.doctor.name }} · {{ it.doctor.title }}（{{ it.doctor.department }}）</div>
          <div class="status">{{ it.status }}</div>
        </div>
        <div class="row2">
          <span>预约号：{{ it.appointment_no }}</span>
          <span>时间：{{ it.appointment_date }}</span>
          <span>费用：¥{{ it.fee }}</span>
        </div>
        <div class="row3" v-if="it.symptoms">症状：{{ it.symptoms }}</div>
        <div class="row3" v-if="it.remark">备注：{{ it.remark }}</div>
      </div>
    </div>

    <!-- 迭代器分组显示模式 -->
    <div v-else class="groups">
      <div v-for="group in groupedAppointments" :key="group.groupName" class="group">
        <div v-if="useIteratorMode && group.groupName !== 'all'" class="group-header">
          <h3>{{ getStatusName(group.groupName) }}</h3>
          <span class="count">{{ group.count }} 个预约</span>
        </div>

        <div class="list">
          <div v-for="it in group.appointments" :key="it.appointment_no" class="card">
            <div class="row1">
              <div class="doctor">{{ it.doctor?.name || it.doctor_name }} · {{ it.doctor?.title || it.doctor_title }}（{{ it.doctor?.department || it.doctor_department }}）</div>
              <div class="status" :style="{ color: it.statusColor || '#409eff' }">{{ getStatusName(it.status) }}</div>
            </div>
            <div class="row2">
              <span>预约号：{{ it.appointment_no }}</span>
              <span>时间：{{ it.formattedDate || it.appointment_date }}</span>
              <span>费用：¥{{ it.fee }}</span>
            </div>
            <div class="row3" v-if="it.symptoms">症状：{{ it.symptoms }}</div>
            <div class="row3" v-if="it.remark">备注：{{ it.remark }}</div>

            <!-- 预约操作按钮 -->
            <div class="appointment-actions" v-if="it.status === 'pending' || it.status === 'confirmed'">
              <el-button
                size="small"
                type="danger"
                @click="confirmCancelAppointment(it)"
              >
                取消预约
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 迭代器状态信息 -->
    <div v-if="useIteratorMode && items.length > 0" class="iterator-info">
      <el-card>
        <template #header>
          <span>🔄 迭代器模式状态</span>
        </template>
        <p>总预约数：{{ items.length }}</p>
        <p>分组数量：{{ groupedAppointments.length }}</p>
        <p>模式：{{ useIteratorMode ? '按状态分组' : '普通列表' }}</p>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.my-appts { max-width: 960px; margin: 0 auto; padding: 20px; }
.empty { color: #909399; padding: 20px 0; }
.list { display: flex; flex-direction: column; gap: 12px; }
.card { border: 1px solid #ebeef5; border-radius: 6px; padding: 12px; background: #fff; }
.row1 { display: flex; justify-content: space-between; font-weight: 600; }
.row2 { display: flex; gap: 16px; margin-top: 8px; color: #606266; }
.row3 { margin-top: 6px; color: #606266; }
.doctor { color: #303133; }
.status { color: #409eff; }

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.empty {
  color: #909399;
  padding: 20px 0;
  text-align: center;
}

.groups {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.group {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.group-header {
  background: #f8f9fa;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.group-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.count {
  color: #909399;
  font-size: 14px;
}

.list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px;
}

.card {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 12px;
  background: #fff;
  transition: all 0.3s;
}

.card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.row1 {
  display: flex;
  justify-content: space-between;
  font-weight: 600;
}

.row2 {
  display: flex;
  gap: 16px;
  margin-top: 8px;
  color: #606266;
}

.row3 {
  margin-top: 6px;
  color: #606266;
}

.doctor {
  color: #303133;
}

.status {
  font-weight: bold;
}

.iterator-info {
  margin-top: 20px;
}

.iterator-info .el-card {
  max-width: 300px;
  margin: 0 auto;
}

.iterator-info p {
  margin: 5px 0;
  color: #606266;
}

.appointment-actions {
  margin-top: 10px;
  text-align: right;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
}
</style>


